#include"tcpClient.h"
#include"logger.h"

#include "ipAddressPort.h"
#include "msg.h"

#include<sys/socket.h>  //socket
#include<netinet/in.h>  //sockaddr_in
#include<arpa/inet.h>   //h to n s
#include<cstring>
#include<unistd.h>      //close
TcpClient::TcpClient(const IpAddressPort& ipAddressPort)
{
    m_sfd = socket(AF_INET, SOCK_STREAM, 0);
    if(-1 == m_sfd)LOG_FATAL << strerror(errno);
    struct sockaddr_in ser_addr;
    memset(&ser_addr, 0, sizeof(ser_addr));
    ser_addr.sin_family = AF_INET;
    ser_addr.sin_port = htons(ipAddressPort.GetPort());
    ser_addr.sin_addr.s_addr = inet_addr(ipAddressPort.GetIpAddress().c_str());
    socklen_t sock_len = sizeof(ser_addr);
    if(-1 == connect(m_sfd, (struct sockaddr*)&ser_addr, sizeof(ser_addr)))
    {
        LOG_FATAL << strerror(errno);
    }
    LOG_INFO << "connect to " << ipAddressPort.ToString() << " success!";
}
TcpClient::~TcpClient()
{
    if(-1 == close(m_sfd))LOG_FATAL << strerror(errno);
}
int TcpClient::SendMsg(const std::string & msg)
{
    /* send */
    int numOfSendByte = send(m_sfd, msg.c_str(), strlen(msg.c_str()), 0);
    if(-1 == numOfSendByte)LOG_ERROR << strerror(errno);
    return numOfSendByte;
}
/* 由于收到的字符串可能是变长的，用string接收不便，所以自创struct组合buf+len结构体返回 */
Msg TcpClient::RecvMsg()
{
    /* recv */
    char buf[LARGE_BUF_LEN] = {0};

    int numOfRecvByte = recv(m_sfd, buf, LARGE_BUF_LEN, 0);
    if(-1 == numOfRecvByte)LOG_ERROR << strerror(errno);
    return Msg{buf, numOfRecvByte};
}

#define __TEST__
#ifdef __TEST__
int main()
{
    IpAddressPort ser("127.0.0.1", 5000);
    TcpClient client(ser);
    client.SendMsg("hello world");
    return 0;
}
#endif